/*
* @Author: wuxianyu
* @Date:   2017-02-16 09:31:28
* @Last Modified by:   zrug
* @Last Modified time: 2017-02-26 17:01:00
*/
angular.module('app')
  .directive('tinyImage', function($compile, ngDialog, uiLoad) {
    // build 上传图片模板
    function build(list, readonly) {
      var tpl = [];

      angular.forEach(list, function(value, key) {
        if(value == undefined){
          return
        }
        tpl.push('<div class="tiny-image-panel">')
        if (!readonly) {
          tpl.push('<p><i class="fa fa-trash-o" ng-click="trashImage($event,key)"></i></p>')
        }
        tpl.push('<img src="' + value + '" ng-click="checkImage($event)">')
        tpl.push('</div>')
      });
      if (!readonly) {
        tpl.push('<div class="tiny-image-panel upload-image-panel" ng-click="uploadClick($event)">')
        tpl.push('<img src="/css/directives/tiny-image/upload.png">')
        tpl.push('</div>')
      }

      return tpl = tpl.join("");
    }

    //当指令中的子元素新增或者删除时，调用绑定的change回调方法（发送绑定的事件）。返回对应的数据
    function callback($scope, $elem) {
      // debugger;
      var all = $elem.find("img");
      all = angular.extend([], all);
      all.pop();
      var $list = [];
      angular.forEach(all, function(value, key) {
        $list.push(value.src);
      })
      var onChange = $elem.attr('on-change');
      if (!!onChange) {
        $scope.$emit(onChange, {
          list: $list
        });
      }
    }

    function _compile($scope, $elem, $attrs, list, height, width, readonly){
      var newElem = $compile(build(list, readonly))($scope);
      newElem.find("img").height(height);
      newElem.find("img").width(width);

      $elem.contents().remove();
      $elem.append(newElem);
    }
    return {
      restrict: 'E',
      template: '',
      replace: true,
      compile: function tinyImageCompile(tElm, tAttrs){
        return function($scope, $elem, $attrs) {
          var width = !!$attrs.width ? $attrs.width : '100px',
            height = !!$attrs.height ? $attrs.height : '100px',
            list, readonly = false;
            // debugger;
          if (!$attrs.source) {
            list = [];
          } else {
            list = angular.extend({}, !$scope[$attrs.source] ? {} : $scope[$attrs.source]);
          }

          if (!!$attrs.readonly) {
            readonly = true;
          }

          _compile($scope, $elem, $attrs, list, height, width, readonly)

          if (!!$attrs.source) {
            $scope.$watch($attrs.source,function(imglist){
              _compile($scope, $elem, $attrs, imglist, height, width, readonly)
            })
          }

          // 点击删除图片icon
          $scope.trashImage = function(ev,index) {
            ngDialog.openConfirm({
              template: '\
                  <p>你确定删除此图片？</p>\
                  <div class="ngdialog-buttons">\
                      <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">否</button>\
                      <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(1)">确定</button>\
                  </div>',
              plain: true
            }).then(function() {
              var tinyImage = angular.element(ev.currentTarget).parents("tiny-image");
              angular.element(ev.currentTarget).parents(".tiny-image-panel").remove();

              callback($scope, tinyImage);

            }, function(reason) {
              console.log('Modal promise rejected. Reason: ', reason);
            });
          }

          $scope.checkImage = function(ev){
            var src = ev.currentTarget.src;
            var i = new Image();
            i.onload = function(e){
              ngDialog.openConfirm({
                template: '\
                    <div style="margin-bottom:20px;"><img src="'+src+'"></div>\
                    <div class="ngdialog-buttons">\
                        <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">关闭</button>\
                    </div>',
                plain: true,
                width: e.target.width + 60
              });
            }
            i.src = src;
          }

          // 点击上传图片触发
          $scope.uploadClick = function(ev) {
            ngDialog.openConfirm({
              template: 'js/module/upload/upload.html',
              resolve: {
                load: function() {
                  return uiLoad.load(['js/module/upload/upload.js'])
                },
                deps: ['$ocLazyLoad',
                  function($ocLazyLoad) {
                    return $ocLazyLoad.load('angularFileUpload').then(
                      function() {
                        return $ocLazyLoad.load('js/module/upload/upload.js');
                      }
                    );
                  }
                ]
              },
              scope: $scope,
              width: 1200,
              height: 600
            }).then(function(uploader) {
              var filelist = [];
              $.each(uploader.queue, function(i, I) {
                var res = JSON.parse(I._xhr.response)
                if (res.code == "0") {
                  filelist.push(res.res.data.imgList[0]);
                }
              });

              var newElem = $compile(build(filelist, readonly))($scope);
              newElem.find("img").height(height);
              newElem.find("img").width(width);

              // angular.element(ev.currentTarget).parents("tiny-image").html("").append(newElem);
              var tinyImage = angular.element(ev.currentTarget).parents("tiny-image");
              angular.element(ev.currentTarget).remove();
              tinyImage.append(newElem);

              callback($scope, tinyImage);
              // $scope.data.House = filelist;
              // $scope.HouseImgNum = $scope.data.House.length;
              console.log('Modal promise resolved. Value: ', filelist);
            }, function(reason) {
              console.log('Modal promise rejected. Reason: ', reason);
            });
          }
        }
      }
    };
  });
